import { app, shell, BrowserWindow, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import log from '@/utils/log'
import icon from '@resources/icon.png?asset'
import { createDefaultTray } from '@/tray'
import initIpcMain from '@/ipc-main'
import checkForUpdates from '@/updater'
import weChatBot from '@/bot'

let mainWindow = null
function createWindow() {
  if (mainWindow !== null) return
  const primaryDisplay = screen.getPrimaryDisplay()
  let { height: sysHeight } = primaryDisplay.workArea // 获取主显示器的可用高度
  sysHeight -= +import.meta.env.VITE_TITLE_HEIGHT // 减去标题栏高度
  const height = sysHeight < 780 ? sysHeight : 780 // 设置窗口高度为系统可用高度，但不超过780
  // Create the browser window.
  // global.mainWindow = mainWindow // 将 mainWindow 设置为全局变量
  global.mainWindow = mainWindow = new BrowserWindow({
    width: 480,
    height,
    // minWidth: 600,
    // minHeight: 670,
    // maxWidth: 600,
    // maxHeight: 670,
    resizable: false, // 禁止调整窗口大小
    maximizable: false, // 禁止最大化
    show: false, // 先隐藏窗口
    alwaysOnTop: is.dev, // 窗口置顶
    transparent: false, // 窗口透明
    autoHideMenuBar: true, // 隐藏菜单栏
    titleBarStyle: 'hidden', // 隐藏标题栏
    titleBarOverlay: {
      // 自定义标题栏
      color: '#1b1b1f00', // 标题栏背景色
      symbolColor: '#000', // 标题栏图标颜色
      height: +import.meta.env.VITE_TITLE_HEIGHT // 标题栏高度
    },
    ...(process.platform === 'linux' ? { icon } : {}),
    // ...(process.platform !== 'darwin' ? { titleBarOverlay: true } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'), // Preload script
      sandbox: false, // 禁用沙箱
      nodeIntegration: false, // 允许在渲染进程中使用 Node.js API
      contextIsolation: true, // 禁用上下文隔离
      webSecurity: false // 禁用同源策略
    }
  })

  // 设置窗口标题为 electron-builder.yml 中的 name
  mainWindow.setTitle(app.getName())

  // 检查更新
  try {
    checkForUpdates(mainWindow)
  } catch (error) {
    log.error('❌❌❌checkForUpdates error', error)
  }

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.on('close', (event) => {
    event.preventDefault()
    mainWindow.hide()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
    log.debug('main window closed')
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 尝试获取单实例锁
  if (!app.requestSingleInstanceLock()) {
    // 如果获取失败，则退出
    return app.quit()
  }

  // 当运行第二个实例时, 将会聚焦到 mainWindow 这个窗口
  // eslint-disable-next-line no-unused-vars
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      // 是否最小化
      if (mainWindow.isMinimized()) mainWindow.restore()
      // 窗口是否可见
      if (!mainWindow.isVisible()) mainWindow.show()
      mainWindow.focus()
    }
  })

  // Set app user model id for windows
  electronApp.setAppUserModelId('cn.lincq.wechat-bot')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // 创建窗口
  createWindow()
  // 初始化 ipcMain
  initIpcMain()
  // 创建系统托盘
  createDefaultTray()
  // 初始化微信机器人
  weChatBot()
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    if (BrowserWindow.getAllWindows().length !== 0) app.quit()
  }
})

app.on('before-quit', () => {
  mainWindow?.destroy()
  mainWindow = null
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
